package com.pot.admin.controller.system;
import cn.hutool.jwt.JWT;
import com.pot.common.aop.NotLogin;
import com.pot.common.aop.NotPower;
import com.pot.admin.service.ISystemLoginService;
import com.pot.admin.validate.system.SystemAdminLoginsValidate;
import com.pot.admin.vo.system.SystemCaptchaVo;
import com.pot.admin.vo.system.SystemLoginVo;
import com.pot.admin.vo.result.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/system")
@Api(tags = "系统登录管理")
public class SystemLoginController {

    @Resource
    ISystemLoginService iSystemLoginService;

    @Autowired
    AuthenticationManager authenticationManager;


    @NotLogin
    @GetMapping("/captcha")
    @ApiOperation(value="取验证码")
    public AjaxResult<SystemCaptchaVo> captcha() {
        SystemCaptchaVo vo = iSystemLoginService.captcha();
        return AjaxResult.success(vo);
    }

    @NotLogin
    @PostMapping("/login")
    @ApiOperation(value="登录系统")
    public AjaxResult<SystemLoginVo> login(@Validated() @RequestBody SystemAdminLoginsValidate loginsValidate) {

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginsValidate.getUsername(), loginsValidate.getPassword());
        authenticationManager.authenticate(authenticationToken);

        //上一步没有抛出异常说明认证成功，我们向用户颁发jwt令牌
        String token = JWT.create()
                .setPayload("username", loginsValidate.getUsername())
                .setKey("MyConstant.JWT_SIGN_KEY".getBytes(StandardCharsets.UTF_8))
                .sign();




        SystemLoginVo vo = iSystemLoginService.login(loginsValidate);
        return AjaxResult.success(vo);
    }

    @NotPower
    @PostMapping("/logout")
    @ApiOperation(value="退出登录")
    public AjaxResult<Object> logout(HttpServletRequest request) {
        SecurityContextHolder.clearContext();

//        iSystemLoginService.logout(request.getHeader("token"));
        return AjaxResult.success();
    }

}
